/*
 * @Description: 文件表格
 * @Author: Rfan
 * @Date: 2022-01-25 18:02:15
 * @LastEditTime: 2022-06-22 11:28:03
 */

import { useEffect, useState } from 'react';
import { Button, Space, Table } from 'antd';
import { TableRowSelection } from 'antd/lib/table/interface';
import classNames from 'classnames/bind';
import { displayTitle, showKeysList } from '@/utils/list';
import { useLevelLayoutContext } from '../contexts/LevelLayoutContext';

import styles from '../styles/fileLevelTable.module.scss';
import { fetchArchivesLevelWithPage, fetchDownLevelList } from '@/api/archives/archives';

const cx = classNames.bind(styles);

const { Column } = Table;

const FileTable = (props: any) => {
  const { base, selectChange } = props;
  const { getSelectedKeys, showAddTransfer, setLevelSelectKey } = useLevelLayoutContext();

  const [loading, setLoading] = useState(false);
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  const [fieldList, setFieldList] = useState([]);
  const [listQuery, setListQuery] = useState<any>({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });
  const [downLevel, setDownLevel] = useState<number>(0);

  /**
   * @description: 选中的keys
   */
  const selectedRowKeys = getSelectedKeys(base.level);
  /**
   * @description: 设置当前层级选中的keys
   * @param {number[]} 选中的keys
   */
  const setSelectedRowKeys: (keys: number[]) => void = setLevelSelectKey(base.level);

  /**
   * @description: 案卷表格选中相关
   * @param {number} selectedKeys
   * @return {*}
   */
  const onSelectChange = (selectedKeys: number[]) => {
    console.log('onSelectChange', selectedKeys);

    const _selectedRowKeys = [...selectedRowKeys];
    if (_selectedRowKeys.indexOf(selectedKeys[0]) < 0) {
      setSelectedRowKeys(selectedKeys);
    }
  };

  const rowSelection: TableRowSelection<any> = {
    type: 'radio',
    selectedRowKeys,
    onChange: onSelectChange
  };

  useEffect(() => {
    if (base) {
      setListQuery((state: any) => {
        return {
          ...state,
          param: { ...base, level: base.level }
        };
      });
    }
  }, [base]);

  useEffect(() => {
    if (listQuery?.param && JSON.stringify(listQuery.param) !== '{}') {
      setLoading(true);
      if (listQuery.param.downLevelId) {
        fetchDownLevelList(listQuery)
          .then((res: any) => {
            const _data = res.data;
            setList(_data.results.data);
            setTotal(_data.totalCount);
            setFieldList(_data.results.fields);
            setDownLevel(_data.results.downLevel.level);
            setSelectedRowKeys([_data.results.data[0].id]);
            selectChange([_data.results.data[0].row_id, _data.results.downLevel.level]);
          })
          .finally(() => {
            setLoading(false);
          });
      } else {
        fetchArchivesLevelWithPage(listQuery)
          .then((res: any) => {
            const _data = res.data;
            if (_data.results) {
              setList(_data.results.data);
              setTotal(_data.totalCount);
              setFieldList(_data.results.fields);
              setDownLevel(_data.results.downLevel.level);
              setSelectedRowKeys([_data.results.data[0].id]);
              selectChange([_data.results.data[0].row_id, _data.results.downLevel.level]);
            }
          })
          .finally(() => {
            setLoading(false);
          });
      }
    }
  }, [listQuery]);

  /**
   * @description: 案卷列表选中条目方法
   * @param {any} record 选中的条目
   */
  const selectRow = (record: any) => {
    console.log('selectRow', record, record.id);

    const _selectedRowKeys = [...selectedRowKeys];
    if (_selectedRowKeys.indexOf(record.id) < 0) {
      setSelectedRowKeys([record.id]);
      selectChange([record.row_id, downLevel]);
    }
  };

  // 切换页码触发
  const pageChange = (page: number, _pageSize: number) => {
    setListQuery([{ key: 'pageNo', value: page }]);
  };

  return (
    <div className={cx('file-wrap')}>
      <div className={cx('table-header')}>
        <div className={cx('title')}>案卷列表</div>
        <div className={cx('opearte')}>
          <Space>
            <Button>登记</Button>
            <Button
              onClick={() => {
                showAddTransfer(base.levelNum === 1);
              }}
            >
              在线移交
            </Button>
          </Space>
        </div>
      </div>
      <Table
        dataSource={list}
        loading={loading}
        rowKey="id"
        size="small"
        rowSelection={rowSelection}
        scroll={{ x: 'max-content' }}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
        onRow={(record) => ({
          onClick: () => {
            selectRow(record);
          }
        })}
      >
        {showKeysList(list[0], fieldList).map((key) => (
          <Column title={displayTitle(key, fieldList)} dataIndex={key} key={key} align="center" />
        ))}
        {list.length > 0 && (
          <Column
            title="操作"
            key="action"
            align="center"
            fixed="right"
            render={() => {
              return (
                <Space>
                  <Button type="text" danger disabled>
                    删除
                  </Button>
                </Space>
              );
            }}
          />
        )}
      </Table>
    </div>
  );
};

export default FileTable;
